package com.zlt.bkparking.service.impl;

import com.zlt.bkparking.dto.*;
import com.zlt.bkparking.entity.*;
import com.zlt.bkparking.mapper.AdminMapper;
import com.zlt.bkparking.mapper.BackUserMapper;
import com.zlt.bkparking.mapper.PermissionMapper;
import com.zlt.bkparking.mapper.RoleMapper;
import com.zlt.bkparking.service.AdminService;
import com.zlt.bkparking.utils.MD5Util;
import com.zlt.bkparking.utils.StringUtil;
import com.zlt.bkparking.vo.BusinessUserVO;
import com.zlt.bkparking.vo.Pager;
import com.zlt.bkparking.vo.PermissionList;
import com.zlt.bkparking.vo.PermissionsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    private AdminService adminService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private BackUserMapper backUserMapper;

    @Autowired
    @Lazy
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean login(AdminUserDTO adminUserDTO) {

        String username = adminUserDTO.getAUsername();
        Admin user = adminService.selectUserByUsername(username);
        if (user == null){
            throw new RuntimeException("账号或密码错误111");
        }
        String s = MD5Util.md5(adminUserDTO.getAPassword(), user.getaSalt(), 10);
        if (!s.equals(user.getaPassword())){
            throw new RuntimeException("账号或密码错误");
        }

        return true;
    }

    @Override
    public Admin selectUserByUsername(String username) {
        Admin o = (Admin) redisTemplate.opsForValue().get("adminUser:username:" + username);
        if (o == null) {
            AdminExample adminExample = new AdminExample();
            adminExample.createCriteria().andAUsernameEqualTo(username);
            List<Admin> users = adminMapper.selectByExample(adminExample);
            o = users.isEmpty() ? null : users.get(0);
            redisTemplate.opsForValue().set("adminUser:username:" + username, o);
        }
        return o;
    }

    @Override
    public List<Role> selectAllRoleList() {
        RoleExample roleExample = new RoleExample();
        List<Role> roleList = roleMapper.selectByExample(roleExample);

        return roleList;
    }

    @Override
    public List<Role> selectAllRoleListearch(String rName) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        if (StringUtil.isNotNull(rName)) {
            criteria.andRNameLike("%"+ rName + "%");
        }
        List<Role> roleList = roleMapper.selectByExample(roleExample);
        return roleList;
    }

    @Override
    public boolean saveRole(RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO,role);
        if (roleDTO.getRId()!=null) {
            roleMapper.updateByPrimaryKeySelective(role);
        } else {
            roleMapper.insertSelective(role);
        }
        return true;
    }

    @Override
    public boolean deleteRole(RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        role.setrState((byte) 1);
        int i = roleMapper.updateByPrimaryKey(role);
        return i>0;
    }

    @Override
    public boolean robakRole(RoleDTO roleDTO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        role.setrState((byte) 0);
        int i = roleMapper.updateByPrimaryKey(role);
        return i>0;
    }

    @Override
    public List<PermissionList> getRoles() {
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andPStateEqualTo((byte)0);
        //所有的权限
        List<Permission> allPermissions = permissionMapper.selectByExample(permissionExample);
        //需要返回的权限
        List<PermissionList> permissionListList = new ArrayList<>();
        allPermissions.forEach( ap-> {
            if (ap.getpLevels().equals((byte)1)){
                PermissionList permissionList = new PermissionList();
                permissionList.setPid(ap.getpId());
                permissionList.setLabel(ap.getpName());
                permissionListList.add(permissionList);
                List<PermissionList> children = new ArrayList<>();
                permissionList.setChildren(children);
            }
        });
        allPermissions.forEach( ap-> {
            if (ap.getpLevels().equals((byte)2)){
                PermissionList permissionList = new PermissionList();
                permissionList.setPid(ap.getpId());
                permissionList.setLabel(ap.getpName());
                permissionListList.forEach( pll -> {
                    if (pll.getPid().equals(ap.getParentId())){
                        pll.getChildren().add(permissionList);
                    }
                });
            }
        });

        return permissionListList;
    }

    @Override
    public List<Permission> getOwnRoles(Integer rId) {
        //当前角色的权限
        List<Permission> permissions = permissionMapper.selectByRid(rId);
        return permissions;
    }

    @Override
    public Boolean saveAdminPer(RolePermissionsVO rolePermissionsVO) {
        Integer rId = rolePermissionsVO.getRId();
        int i =  permissionMapper.deleteRolePermissionsByRid(rId);
        int i2 = 0;
        if (i >= 0){
            for (int i1 = 0; i1 < rolePermissionsVO.getModuleIds().size(); i1++) {
                Long pid = rolePermissionsVO.getModuleIds().get(i1);
                i2 = permissionMapper.insertRolePermissions(rId, pid);
            }

        }
        return i2>=0;
    }

    @Override
    public List<PermissionsVO> getAllPermission() {
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andPStateEqualTo((byte)0);
        //所有的权限
        List<Permission> allPermissions = permissionMapper.selectByExample(permissionExample);
        List<PermissionsVO> permissionsVOS = new ArrayList<>();
        allPermissions.forEach( ap-> {
            if (ap.getpLevels().equals((byte)1)){
                PermissionsVO permissionsVO = new PermissionsVO();
                permissionsVOS.add(permissionsVO);
                permissionsVO.setId(ap.getpId());
                permissionsVO.setPId(ap.getParentId());
                permissionsVO.setName(ap.getpName());
                permissionsVO.setPDesc(ap.getpDesc());
                permissionsVO.setPHref(ap.getpHref());
                permissionsVO.setPIcon(ap.getpIcon());
                permissionsVO.setPLevels(ap.getpLevels());
                permissionsVO.setPState(ap.getpState());
                List<PermissionsVO> children = new ArrayList<>();
                permissionsVO.setChildren(children);
            }
        });
        allPermissions.forEach( ap-> {
            if (ap.getpLevels().equals((byte)2)){
                PermissionsVO permissionsVO = new PermissionsVO();
                permissionsVO.setId(ap.getpId());
                permissionsVO.setPId(ap.getParentId());
                permissionsVO.setName(ap.getpName());
                permissionsVO.setPDesc(ap.getpDesc());
                permissionsVO.setPHref(ap.getpHref());
                permissionsVO.setPIcon(ap.getpIcon());
                permissionsVO.setPLevels(ap.getpLevels());
                permissionsVO.setPState(ap.getpState());
                permissionsVOS.forEach( pll -> {
                    if (pll.getId().equals(ap.getParentId())){
                        pll.getChildren().add(permissionsVO);
                    }
                });
            }
        });
        return permissionsVOS;
    }

    @Override
    public List<Permission> getNodes() {
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andPStateEqualTo((byte)0);
        criteria.andPLevelsEqualTo((byte)1);
        //所有的权限
        List<Permission> allPermissions = permissionMapper.selectByExample(permissionExample);
        return allPermissions;
    }

    @Override
    public Permission getPermissionByPid(Long pid) {
        Permission permission = permissionMapper.selectByPrimaryKey(pid);
        return permission;
    }

    @Override
    public Boolean savePermission(PrDTO permissionsDTO) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionsDTO,permission);
        if (permission.getpId() == 0) {
            permission.setpId(null);
            int insert = permissionMapper.insertSelective(permission);
            return insert > 0;
        }
        int i = permissionMapper.updateByPrimaryKeySelective(permission);
        return i > 0 ;
    }

    @Override
    public Pager<BusinessUserVO> getAllUser(BusinessUserDTO businessUserDTO) {
        Pager<BusinessUserVO> page = new Pager<>();
        page.setLimit(businessUserDTO.getLimit());
        page.setPage(businessUserDTO.getPage());

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteriaR = roleExample.createCriteria();
        criteriaR.andRNameEqualTo("业务员");
        List<Role> roleList = roleMapper.selectByExample(roleExample);
        long count = backUserMapper.countByBusinessUserDTOByRole(businessUserDTO,roleList.get(0).getrId());
//        long count = backUserMapper.countByExample(backUserExample);
        page.setTotalCount(count);

        page.setPageCount((page.getTotalCount() - 1 )/ page.getLimit() + 1);
        List<BackUser> backUsers = backUserMapper.selectByExampleByRole(businessUserDTO , roleList.get(0).getrId());
//        List<BackUser> backUsers = backUserMapper.selectByExample(backUserExample);
        System.out.println(backUsers.size());
        List<BackUser> backUsers1 = new ArrayList<>();
        if ((page.getPage() - 1) * page.getLimit() + page.getLimit() + 1 <= backUsers.size()) {
            backUsers1 = backUsers.subList((page.getPage() - 1) * page.getLimit(), (page.getPage() - 1) * page.getLimit() + page.getLimit() );
        }
        if ((page.getPage() - 1) * page.getLimit() + page.getLimit() + 1 > backUsers.size()) {
            backUsers1 = backUsers.subList((page.getPage() - 1) * page.getLimit(), backUsers.size());
        }
        List<BusinessUserVO> businessUserVOList = new ArrayList<>();
        backUsers1.forEach( b1 -> {
            BusinessUserVO businessUserVO = new BusinessUserVO();
            BeanUtils.copyProperties(b1,businessUserVO);
            businessUserVOList.add(businessUserVO);
        });
        page.setData(businessUserVOList);
        return page;
    }

    @Override
    public Boolean userSave(BusinessUserDTO businessUserDTO) {
        if (businessUserDTO.getBuId() == 0){
            businessUserDTO.setBuId(null);
        }
        BackUser backUser = new BackUser();
        BeanUtils.copyProperties(businessUserDTO, backUser);
        if (businessUserDTO.getBuId() == null) {

            backUser.setBuSalt(StringUtil.randomStr(6));
            backUser.setBuPassword(MD5Util.md5("123456", backUser.getBuSalt(), 10));
            backUserMapper.insertSelectiveReturnKey(backUser);
            if (backUser.getBuId() != null) {
                RoleExample roleExample = new RoleExample();
                RoleExample.Criteria criteria = roleExample.createCriteria();
                criteria.andRNameEqualTo("业务员");
                List<Role> roleList = roleMapper.selectByExample(roleExample);
                int i = backUserMapper.insertUserRole(backUser.getBuId(), roleList.get(0).getrId());
                return i>0;
            }
        }
        int i = backUserMapper.updateByPrimaryKeySelective(backUser);

        return i>0;
    }

    @Override
    public Boolean userDeleteAdmin(BusinessUserDTO businessUserDTO) {
        BackUser backUser = new BackUser();
        BeanUtils.copyProperties(businessUserDTO, backUser);
        int i = backUserMapper.updateByPrimaryKeySelective(backUser);
        return i>0;
    }

    @Override
    public Boolean pwd(BusinessUserDTO businessUserDTO) {
        BackUser backUser = new BackUser();
        BeanUtils.copyProperties(businessUserDTO, backUser);
        backUser.setBuSalt(StringUtil.randomStr(6));
        backUser.setBuPassword(MD5Util.md5("123456",backUser.getBuSalt(),10));
        int i = backUserMapper.updateByPrimaryKeySelective(backUser);
        return i>0;
    }
}
